﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeatherPrediction;
using System.Threading;
using System.Net;
using System.Xml.Linq;

namespace Weather_Prediction
{
        

    public partial class WebForm1 : System.Web.UI.Page
    {
        #region Members

        ParseForecast weatherForecast = new ParseForecast();
        WebUserControlDayForeCast userControl = new WebUserControlDayForeCast();
        ParseResult countryCodeResult;
        string countryEnglishName;
        string languageCodes;

        
        string urlForForcast;
        string countryCode;
        

        #endregion Members
        protected void Page_Load(object sender, EventArgs e)
        {
            //call this function from javaScript to draw the map
            ClientScript.RegisterStartupScript(this.GetType(), "initializeMap", "initializeMap();", true);            
        }


        public static Coordinate GetCoordinates(string region)
        {
            using (var client = new WebClient())
            {

                string uri = "http://maps.google.com/maps/geo?q='" + region + "'&output=csv&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA";

                string[] geocodeInfo = client.DownloadString(uri).Split(',');

                return new Coordinate(Convert.ToDouble(geocodeInfo[2]), Convert.ToDouble(geocodeInfo[3]));
            }
        }

        public struct Coordinate
        {
            private double lat;
            private double lng;

            public Coordinate(double latitude, double longitude)
            {
                lat = latitude;
                lng = longitude;

            }

            public double Latitude { get { return lat; } set { lat = value; } }
            public double Longitude { get { return lng; } set { lng = value; } }

        }

        
        protected void ClickSearch(object sender, EventArgs e)
        {
            try
            {
                //get location on the map
                double Lat = GetCoordinates(tbLocation.Text).Latitude;
                double Lng = GetCoordinates(tbLocation.Text).Longitude;

                //call this function from javaScript to draw the map
                ClientScript.RegisterStartupScript(this.GetType(), "findLocation", "findLocation('" + Lat + "','" + Lng + "');", true);               

                //get the country code of the location 
                getCountryCode(tbLocation.Text);

                updateDateForecast(tbLocation.Text, countryEnglishName);
            }
            catch (Exception)
            {
                //TODO
            }  
        }

        
        private void updateDateForecast(string location, string countryEnglishName)
        {
            //get wheather forecast for the state 
            // the url look like this http://api.wunderground.com/api/46656caf5b865813/forecast/lang:DL/q/Germany/Nuremberg.json 
            urlForForcast = "http://api.wunderground.com/api/46656caf5b865813/forecast/lang:" + languageCodes + "/q/" + countryEnglishName + "/" + location + ".json";
            ParseForecast wheatherforecast = Communication.MakeRequestForecast(urlForForcast);

            //read the result of the request
            weatherForecast = Communication.getResponseOfRequestForecast(wheatherforecast);

            //display the data
            displayTheDataOnTheView(weatherForecast.forecastDay.forecastDay.listForecastDay);
        }

        private void getCountryCode(string location)
        {
            //get country code and name from the location 
            string urlToGetLanguageCode = "http://autocomplete.wunderground.com/aq?query=" + location;
            countryCodeResult = Communication.MakeRequestCountryCode(urlToGetLanguageCode);

            //read the result
            countryCode = Communication.getResponseOfRequestCountryCode(countryCodeResult);

            countryEnglishName = Communication.getResponseOfRequestCountryName(countryCodeResult);
            languageCodes = getLanguageCode(countryEnglishName); 
        }

        private void updateDataOfForecast()
        {

        }

        private string getLanguageCode(string code)
        {
            if (code == "Germany")
            {
                return "DL";
            }
            else if (code == "France")
            {
                return "FR";
            }
            else
            {
                return "EN";
            }
        }

        private void displayTheDataOnTheView(forecastOfOneday[] forecastOfOneday)
        {
            int entriesCount = forecastOfOneday.Length;
            setTabel(entriesCount, forecastOfOneday);
        }

        private void setTabel(int entriesCount, forecastOfOneday[] forecastOfOneday)
        {
            // Generate rows and cells.           
            int numrows = entriesCount/3;
            int numcells = 3;
            int index = 0;
            for (int j = 0; j < numrows; j++)
            {
                TableRow r = new TableRow();
                for (int i = 0; i < numcells; i++)
                {
                    userControl = (WebUserControlDayForeCast)LoadControl("WebUserControlDayForeCast.ascx");

                    userControl.fillContent(forecastOfOneday[index]);
                    TableCell c = new TableCell();
                    c.Controls.Add(userControl);
                    r.Cells.Add(c);
                    
                    index++;
                }
                PlaceHolderForUserControl.Rows.Add(r);
            }
        }

       

        private void setTextOfLabels(string textToDisplay, Label labelToSet)
        {
            labelToSet.Text = textToDisplay;
        }
    }
}